import os
import boto3
from botocore.config import Config


# upload file

def get_base_url(properties):
    domain = properties.get('domain')
    endpoint = properties.get('endpoint')
    header = "https://" if properties.get('isHttps') == 'Y' else "http://"

    # cloud oss
    if any(cloud_service in endpoint for cloud_service in ["aliyun", "qcloud", "qiniu", "obs"]):
        if domain:
            return header + domain
        return header + properties.get('bucketName') + "." + endpoint

    # minio
    if domain:
        return header + domain + "/" + properties.get('bucketName')

    return header + endpoint + "/" + properties.get('bucketName')


def get_bucket(properties):
    endpoint = properties.get('endpoint')
    access_key = properties.get('accessKey')
    secret_key = properties.get('secretKey')
    bucket_name = properties.get('bucketName')
    prefix = properties.get('prefix')
    header = "https://" if properties.get('isHttps') == 'Y' else "http://"
    endpoint_url = header + endpoint
    s3_client = boto3.client('s3', aws_access_key_id=access_key, aws_secret_access_key=secret_key,
                             endpoint_url=endpoint_url,
                             config=Config(s3={"addressing_style": "virtual", "signature_version": 's3v4'}))

    base_url = get_base_url(properties)
    return s3_client, bucket_name, base_url, prefix


def upload_file(s3_client, bucket_name, key, filename):
    try:
        s3_client.upload_file(filename, bucket_name, key)
    finally:
        # delete file
        if os.path.exists(filename):
            os.remove(filename)
